package com.iptv.grape.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import static android.content.Context.MODE_PRIVATE;

// 读取Assets下的Json文件
public class ReadJsonFile {
    // 读取Assets下的Json文件
    public static String readFileByAssets(String fileName, Context context) {
        InputStream input = null;
        try {
            //taipingyang.json文件名称
            input = context.getAssets().open(fileName);
            String json = convertStreamToString(input);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final String PackageName = "com.iptv.grape";


    // 读取指定的图片
    public static Bitmap getRunImgFile(){
        return getRunImgFile("runimg.jpg");
    }

    public static Bitmap getRunImgFile(String fileName){
        Bitmap bitmap = null;
        String filePath = Environment.getDataDirectory() + "/data/" + PackageName + "/files/" + fileName;
        try
        {
            File file = new File(filePath);
            if(file.exists())
            {
                bitmap = BitmapFactory.decodeFile(filePath);
            }
        } catch (Exception e)
        {
            // TODO: handle exception
        }
        return bitmap;
    }

    // 将图片写入文件
    public static void writeImgToFile(String fileName, Bitmap bitmap){
        try {
            //String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
            String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
            //File file = new File(path + fileName);
            makeFilePath(path, fileName);
            AppLog.getCurLog().out(path + fileName);
            FileOutputStream fs = new FileOutputStream(path + fileName);


            //FileOutputStream fs = activity.openFileOutput(fileName, MODE_PRIVATE);
            //byte[] data = json.getBytes();
            try {
                // 写文件
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fs);
                fs.flush();
                fs.close();
                AppLog.getCurLog().out("File Img OK----------------");
            } catch (IOException e) {
                e.printStackTrace();
                AppLog.getCurLog().out("ERROR_IOException" + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            AppLog.getCurLog().out("ERROR_FileNotFoundException" + e.getMessage());
        }
    }

    // 写入文本文件
    public static void writeFile(String fileName, String json){
        try {
            //String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
            String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
            //File file = new File(path + fileName);
            makeFilePath(path, fileName);
            AppLog.getCurLog().out(path + fileName);
            FileOutputStream fs = new FileOutputStream(path + fileName);
            //FileOutputStream fs = activity.openFileOutput(fileName, MODE_PRIVATE);
            byte[] data = json.getBytes();
            try {
                // 写文件
                fs.write(data);
                fs.flush();
                fs.close();
                AppLog.getCurLog().out("File OK----------------");
            } catch (IOException e) {
                e.printStackTrace();
                AppLog.getCurLog().out("ERROR_IOException" + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            AppLog.getCurLog().out("ERROR_FileNotFoundException" + e.getMessage());
        }
    }

    // 生成文件
    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            //Log.i("error:", e+"");
        }
    }
    // 写入文本文件
    public static void writeFile(String fileName, String json, Activity activity) {
        try {

            FileOutputStream fs = activity.openFileOutput(fileName, MODE_PRIVATE);
            byte[] data = json.getBytes();
            try {
                // 写文件
                fs.write(data);
                fs.flush();
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 读取文本文件
    public static String readFile(String fileName, Activity activity) {

        try {
            FileInputStream inputStream = activity.openFileInput(fileName);
            String json = convertStreamToString(inputStream);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    // 读取文本文件
    public static String readFile(String fileName) {

        try {
            String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
            AppLog.getCurLog().out(path + fileName);
            FileInputStream inputStream = new FileInputStream(path + fileName);
            String json = convertStreamToString(inputStream);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            AppLog.getCurLog().out(e.getMessage());
            return null;
        }
    }

    // 判断文件是否存在
    public static boolean fileExists(String fileName, Activity activity){
        String json = readFile(fileName,activity);

        return json != null?true:false;
    }

    // 判断文件是否存在
    public static boolean fileExists(String fileName) {
        String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
        File file = new File(path + fileName);

        return file.exists();
    }

    // 删除文件
    public static boolean deleteFile(String fileName) {
        String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
        File file = new File(path + fileName);
        if (file.isFile()) {
            return file.delete();
        }
        return false;
    }

    // 返回指定目录的文件
    public static List<String> getPathList(String name) {
        String path = Environment.getDataDirectory() + "/data/" + PackageName + "/files/";
        List<String> list = new ArrayList<String>();
        File file = new File(path);
        //获取文件夹下的所有文件及目录
        File[] fileList = file.listFiles();
        if(name != null && !"".equals(name)) {
            //遍历文件夹下的所有文件及目录
            for (int i = 0; i < fileList.length; i++) {
                //只处理文件不处理目录，并且判断文件名称是否包含name
                if (fileList[i].isFile() && fileList[i].getName().indexOf(name) != -1) {
                    list.add(fileList[i].getName());
                }
            }
        }
        return list;
    }

    private static String convertStreamToString(InputStream is) {
        String s = null;
        try {
            //格式转换
            Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A");
            if (scanner.hasNext()) {
                s = scanner.next();
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }


}
